package com.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

public class ChooseFiveDataUtils {

    private static List<Integer> list = new ArrayList<>();

    private static List<Integer> selectedElementsList = new ArrayList<>();

    private static int targetNumber;

    // 修改为最小值
    private static int closestSum = Integer.MIN_VALUE;

    private static Random random = new Random();


    /**
     * 5个数字之和最接近并且小于指定的值
     *
     * @param args
     */
    public static void main(String[] args) {

        list = Arrays.asList(70, 95, 120, 140, 160, 179, 190, 205, 220, 230, 245, 255, 265, 270, 280);

        List<Integer> integerList = list.stream().sorted().collect(Collectors.toList());
        System.out.println(integerList);

        // 指定的数字
        targetNumber = 995;

        findClosestSum(0, 0);

        System.out.println("选中的元素：" + selectedElementsList);
        System.out.println("元素之和：" + closestSum);
    }

    public static void findClosestSum(int index, int currentSum) {
        if (index == 5) {
            // 修改判断条件
            if (currentSum < targetNumber && currentSum > closestSum) {
                closestSum = currentSum;
                selectedElementsList = new ArrayList<>(list.subList(0, 5));
            }
            return;
        }

        for (int i = index; i < list.size(); i++) {
            swap(index, i);
            findClosestSum(index + 1, currentSum + list.get(index));
            // 恢复列表的顺序
            swap(index, i);
        }
    }

    public static void swap(int i, int j) {
        int temp = list.get(i);
        list.set(i, list.get(j));
        list.set(j, temp);
    }

}
